import {
  ElButton,
  ElIcon,
  ElTag,
  ElTooltip,
  TableV2FixedDir,
  ElMessageBox,
  ElMessage,
  dayjs,
  ElCheckbox,
  ElLink,
  ElSelect,
  ElOption
} from 'element-plus'
import { getFile } from "@/api";
//   @element-plus/icons-vue
import { h } from 'vue'



let tagTypes = [['success', '进行中（待办）'], ['primary', '已完成（已办）'], ['danger', '已到期（未完成）']]

const userAllTaskColumn = {
  "id": "",//任务id    
  "userId": "",//任务所属用户id
  "appointorId": "",//指派人id（自己创建：NULL，被派发：绑定管理员id）
  "workStatusId": "",//任务状态id（0：进行中（待办），1:已完成（已办），2:已逾期（未完成））
  "priorityId": "",//任务的优先级(0:一般，1:重要，2:紧急)
  "attachmentsId": "",//附件id（没有附件默认NULL）
  "title": "",//标题
  "content": "",//任务的详细描述
  "require": "",//任务要求
  "createTime": "",//创建任务的时间戳
  "updateTime": "",//最后一次更新的时间戳
  "endTime": "",//任务结束的时间戳
  "deletionState": ""//逻辑删除（0未删除，1逻辑删除），用来定期清理删除已删除任务的附件
}


export const getColumns = function (router, store) {
  return [

    {
      key: 'checked',
      align: 'center',
      dataKey: "checked",
      fixed: TableV2FixedDir.LEFT,
      width: 50,
      cellRenderer: ({ rowData }) => {

        const onChange = (value) => {
          rowData.checked = value
        }
        return h(ElCheckbox, { onChange, modelValue: rowData.checked })
      },

      headerCellRenderer: () => {
        const onChange = (value) => {

          store.adminWorksList = store.adminWorksList.map(row => {
            row.checked = value
            return row
          });
        }

        const allSelected = store.adminWorksList.every((row) => row.checked)
        const containsChecked = store.adminWorksList.some((row) => row.checked)
        if (!containsChecked) {
          store.isSomeIngChecked = true
        } else {
          store.isSomeIngChecked = false
        }

        return h(ElCheckbox, { onChange, modelValue: allSelected, indeterminate: containsChecked && !allSelected })
      },
    },

    {
      align: 'center',
      width: 150,
      key: "title",
      dataKey: "title",
      title: '任务名称'
    },
    {
      align: 'center',
      width: 150,
      key: "content",
      dataKey: "content",
      title: '任务内容'
    },
    {
      align: 'center',
      width: 150,
      key: "createName",
      dataKey: "createName",
      title: '姓名',
      cellRenderer: ({ cellData }) => {
        return cellData == "" || cellData == null ? "/" : cellData
      }
    },
    {
      align: 'center',
      width: 150,
      key: "attachmentNames",
      dataKey: "attachmentNames",
      title: '附件名',
      cellRenderer: ({ rowData }) => {
        const onClick = () => {
          getFile(rowData.attachmentNames).then(res => {
            let contentType = res.headers['content-type'] || 'application/octet-stream';
            var blob = new Blob([res.data], { type: contentType });
            var a = document.createElement("a");
            const urlObject = URL.createObjectURL(blob);
            a.href = urlObject
            a.download = rowData.attachmentNames;

            a.click();
            URL.revokeObjectURL(urlObject);

          })
        }
        // return rowData.attachmentNames==null||rowData.attachmentNames==""?"/":h(ElSelect,{placeholder:"附件"},rowData.attachmentNames.split(",").map((val)=>(h(ElOption,{ label:val,value:val}))))
        return rowData.attachmentNames == null || rowData.attachmentNames == "" ? "/" : h(ElLink, { onClick, underline:false }, () => rowData.attachmentNames)
      }
    },
    {
      align: 'center',
      width: 150,
      key: "workStatusId",
      dataKey: "workStatusId",
      title: '任务状态',
      cellRenderer: ({ rowData }) => {
        let color = "black;"
        if (rowData.workStatusId == 2) {
          color = "red;"
        }
        return h('div', null, [
          h(ElTag, { type: tagTypes[rowData.workStatusId][0], effect: "dark", round: true, class: "tagStatus" }),
          h('span', { style: `color:${color}` }, tagTypes[rowData.workStatusId][1])
        ]);
      }
    },
    {
      align: 'center',
      width: 150,
      key: "endTime",
      dataKey: "endTime",
      title: '截止时间',
      cellRenderer: ({ rowData }) => {
        return dayjs(rowData.endTime * 1).format('YYYY-MM-DD HH:mm:ss');
      }
    },
    {
      align: 'center',
      width: 150,
      key: "createTime",
      dataKey: "createTime",
      title: '创建时间',
      cellRenderer: ({ rowData }) => {
        return dayjs(rowData.createTime * 1).format('YYYY-MM-DD HH:mm:ss');
      }
    },
    {
      align: 'center',
      width: 150,
      key: "updateTime",
      dataKey: "updateTime",
      title: '完成时间',
      cellRenderer: ({ rowData }) => {
        return rowData.workStatusId == 1 ? dayjs(rowData.updateTime * 1).format('YYYY-MM-DD HH:mm:ss') : "/"
      }
    },
    {
      key: 'operations',
      title: '操作',
      fixed: TableV2FixedDir.RIGHT,
      cellRenderer: ({ rowData }) => {
        const onEditClick = () => {
          router.push({ path: "/editTaskPages", query: { tasks: [JSON.stringify(rowData)] } })
        }

        const onDeleteClick = () => {
          ElMessageBox.confirm('确定删除吗?')
            .then(() => {
              store.deleteTasks({ taskIds: [rowData.id] })
            })
            .catch(() => {
              ElMessage({
                message: '已取消',
                type: 'warning',
              })
            })
        }

        return h('div', null, [
          h(ElButton, { size: "small", onClick: onEditClick }, () => '编辑'),
          h(ElButton, { size: "small", type: "danger", onClick: onDeleteClick }, () => '删除')
        ])
      },
      width: 150,
      align: 'center',

    }
  ]
}




